package com.informatics.polymer.server.imagegeneration;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import org.openscience.cdk.DefaultChemObjectBuilder;
import org.openscience.cdk.interfaces.IMolecule;
import org.openscience.cdk.layout.StructureDiagramGenerator;
import org.openscience.cdk.renderer.Java2DRenderer;
import org.openscience.cdk.renderer.Renderer2DModel;
import org.openscience.cdk.smiles.SmilesParser;

import com.informatics.polymer.server.imagegeneration.sf.structure.cdk.util.ImageKit;

public class ImageGenerator {
	/**
	 * Smiles string to convert to an image.
	 */
	private String smilesString;

	/**
	 * Instantiates an object of type ImageGenerator.
	 * 
	 * @param smile
	 *            - smiles string.
	 */
	public ImageGenerator(final String smile) {
		this.smilesString = smile;
	}

	/**
	 * 
	 * @return String representation of the smiles string.
	 */
	private String getSmilesString() {
		return smilesString;
	}

	/**
	 * Writes out image into WAR folder.
	 * @throws Exception 
	 */
	public void writeOutImage() throws Exception {
		SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder
				.getInstance());
		IMolecule m = sp.parseSmiles(getSmilesString());
		StructureDiagramGenerator sdg = new StructureDiagramGenerator();
		sdg.setMolecule(m);
		sdg.generateCoordinates();
		IMolecule layedOutMol = sdg.getMolecule();
		Renderer2DModel r2dm = new Renderer2DModel();
		r2dm.setShowAromaticity(true);
		Java2DRenderer sr = new Java2DRenderer(r2dm);
		sr.setRenderer2DModel(r2dm);
		BufferedImage bimage = null;
		// paint molecule to java.awt.BufferedImage
		bimage = new BufferedImage(400, 200, BufferedImage.TYPE_BYTE_INDEXED);
		Graphics2D g = bimage.createGraphics();
		g.setBackground(Color.WHITE);
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 400, 200);
		sr.paintMolecule(layedOutMol, g);
		String curDir = new String(System.getProperty("user.dir"));
		String output = curDir+"/RepeatUnitPictures/Test" + ".png";
		ImageKit.writePNG(layedOutMol, 400, 200, output);
	}
	
/*	public static void main(String[]args) throws Exception{
		ImageGenerator imgG = new ImageGenerator("C1=CC=CC=C1");
		imgG.writeOutImage();
	}*/
}
